package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.invoke.LambdaConversionException;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        List<Category> categoryList = categoryMapper.findAll();
        return categoryList;
    }

    @Override
    public void save(Category category) {
        //补齐其他的参数
        category.setId(IdUtil.getSnowflake(1, 1).nextId());//雪花算法
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);
        //调用mapper保存
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
        //修改时间还有修改人的变化
//        category.setUpdateTime(new Date());
//        category.setUpdateUser(1L);
        categoryMapper.updateById(category);
    }

    //    @Override
//    public ResultInfo delete(Long id) {
//        //查看当前分类是否有菜品，如果有，不允许删除本分类，
//       int count1= categoryMapper.countDisByCategoryId(id);
//        if (count1>0) {
//            return ResultInfo.error("当前分类存在菜品，不能删除");
//        }
//       int count2= categoryMapper.countSetmealByCategoryId(id);
//        if (count2>0){
//            return ResultInfo.error("当前分类存在套餐，不能删除");
//        }
//        categoryMapper.delete(id);
//        return ResultInfo.success(null);
//    }
    @Override
    public ResultInfo delete(Long id) {
        //1. 查看当前分类下是否有菜品,如果有,不允许删除本分类  查询dish表
        int count1 = categoryMapper.countDisByCategoryId(id);
        if (count1 > 0) {
            throw new CustomException("当前分类下存在菜品,不能删除");//抛异常
        }

        //2. 查看当前分类下是否有套餐,如果有,不允许删除本分类  查询setmeal表
        int count2 = categoryMapper.countSetmealByCategoryId(id);
        if (count2 > 0) {
            throw new CustomException("当前分类下存在套餐,不能删除");//抛异常
        }

        //3. 当前分类下什么都没有,可以删除
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }

    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType, type);
        return categoryMapper.selectList(wrapper);
    }
}
